package admin.controllers;

import helpers.IdUniqueHelper;

import java.io.IOException;
import java.net.URLDecoder;
import java.util.TreeMap;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import entities.Template;

import admin.forms.TemplateForm;
import admin.models.TemplateModel;

@SuppressWarnings("serial")
public class TemplateAddServlet extends HttpServlet {
	public void doGet(HttpServletRequest request, HttpServletResponse response)
		throws IOException, ServletException {
		TreeMap<String, String> check = new TreeMap<String, String>();
		
		TemplateModel appTemplateModel = TemplateModel.getInstance();
		Template template = new Template();
		
		request.setAttribute("form", "add");
		request.setAttribute("check", check);
		request.setAttribute("template", template);
		try {
			request.getRequestDispatcher("/admin/pages/template_form.jsp").forward(request, response);
		} catch (ServletException e) {
			e.printStackTrace();
		}
	}
	
	public void doPost(HttpServletRequest request, HttpServletResponse response)
		throws IOException, ServletException {
		
		TemplateModel appTemplateModel = TemplateModel.getInstance();
		Template template = new Template();
		//template.setId(IdUniqueHelper.getId());
		template.setId("CRESMRBUN8Y");
		
		TreeMap<String, Object> form = TemplateForm.checkValid(request, template);
		template = (Template) form.get("template");
		TreeMap<String, String> check = (TreeMap<String, String>) form.get("checkValid");
		
		if (check.size() == 0) {
			appTemplateModel.insert(template);
			
			request.setAttribute("success", "Creat new template " + template.getId() + " success");
			
			template = new Template();
		}
		
		request.setAttribute("form", "add");
		request.setAttribute("check", check);
		request.setAttribute("template", template);
		try {
			request.getRequestDispatcher("/admin/pages/template_form.jsp").forward(request, response);
		} catch (ServletException e) {
			e.printStackTrace();
		}
	}
}
